<?php
/**
 * @file user.php
 * @brief 
 * 	stores user functions
 */
require_once('../config.php');
require_once('functions.php');
require_once('class.form.php');

define('MIN_USERNAME_LENGTH', 6); //定义用户名长度限制
define('MAX_USERNAME_LENGTH', 16); //定义用户名长度限制
define('MIN_PASSWORD_LENGTH', 6); //定义用户名长度限制
define('MAX_PASSWORD_LENGTH', 25); //定义用户名长度限制

class User {
	
	public $id;	
	public $username; // login component
	public $password; // login component - encrypted password
	
	public $on_reg_step;//on which registration step? 
	
	public $details; //user information array
	
	
	
	public function User(){
		if(self::isLoggedIn()){
			$this->username = self::getUsername();
			$this->details = $this->getUser($this->username);
			$this->id = $this->details['id'];
			$this->on_reg_step = $this->details['on_reg_step'];
		}else{
			js_redirect('用户未登录，跳转至首页',HOME_URL);
			die();
		}
	}
	
	
	/**
	 * 检查用户是否已登录
	 * @return 
	 * 	true - 用户登录了
	 * 	false - 用户没登陆
	 */
	public static function isLoggedIn(){
		return (isset($_COOKIE["username"]) || isset($_SESSION["username"]));
	}
	
	/**
	 * 获取已登录用户的 username
	 * @return 用户username， 若用户未登录返回 null
	 */
	public static function getUsername(){
		if(isset($_COOKIE['username'])){
			return $_COOKIE['username'];
		}else if(getSession('username')!=null){
			return getSession('username');
		}else{
			return null;
		}
	}
	
	/**
	 * 根据用户username获取用户信息
	 * @param $by
	 * 	the search field to search user by
	 * @return array
	 * 	用户信息array
	 */
	public function getUser($value,$by='username'){
		return DB::queryFirstRow("SELECT * FROM `account` WHERE `".$by."`=%s",$value);
	}
	
	/**
	 * 检查用户是否未完成填写信息
	 * @return true if user have not finished their profile-registration yet
	 */
	function isRookie(){
		return ($this->details['is_rookie'] == 1);
	}
	
	/**
	 * User login, uses the email and password in this class.
	 * 若失败在$_SESSION["login_error"]中保存错误提示
	 * @param $remember
	 * 	是否自动登录 default=false
	 * @return
	 * 	true 登录成功， false 登录失败
	 */
	function login($remember=false){
		
		if(isset($this->username) && isset($this->password)){
						$row = DB::queryFirstRow("SELECT * FROM `account` WHERE `username`=%s",$this->username);
						if($row!=null){
							if($row['is_active'] == 0){
								$this->setLoginError("用户未激活");
								return false;
							}
							$dbusername = $row['username'];
							$dbpassword = $row['password'];
							if($this->username==$dbusername && $this->password==$dbpassword){
								//login successful
								setSession("username", $this->username);
								if($remember){
									//ob_start();
									//cookie must be set before any output
									// 第四个parameter('/')， 是让cookie可以被全站访问
									setcookie("username", $this->username, time()+COOKIE_END_DAY,'/') or die('cannot set cookie');	
								}
								//record last login time
								$now = date('Y-m-d H:i:s');
								DB::update('account', 
											array(
											'last_login' => $now
											), "username=%s", $this->username);
								
								return true;
							}
							else {
								$this->setLoginError("密码不正确");
								return false;
							}
						}
						else {
							$this->setLoginError("用户不存在");
							return false;
						}
					}
					else{
						$this->setLoginError("请输入用户名和密码");
						return false;
					}
	}
	
	
	/**
	 * 注册用户，成功后发送激活邮件并跳转至注册成功页面
	 * @param $username
	 * 	用户名
	 * @param $password
	 * 	密码
	 * @param $password_confirm
	 * 	确认密码
	 * @param $email
	 * 	邮箱
	 * @return
	 * 	true 注册成功， false 注册失败
	 */
	function register($username , $password, $password_confirm,$email){
		require_once(ROOT_DIR.'libs/securimage/securimage.php');
		$securimage = new Securimage();
		/*if ($securimage->check($_POST['captcha_code']) == false) {
		  // the code was incorrect
		  // you should handle the error so that the form processor doesn't continue
		
		  // or you can use the following code if there is no validation or you do not know how
		  $this->setRegError("验证码不正确") ;
		  return false;
		}*/
		$namecheck = DB::queryFirstRow("SELECT `email` FROM `account` WHERE `username` =%s",$username);
		
	    $checkEmail = filter_var( $email, FILTER_VALIDATE_EMAIL );
	
		
		if($namecheck!=null){
			$this->setRegError("此账户已经存在");
		}else{
			if($username && $password && $password_confirm && $email){
				if(sizeof($username) > MAX_USERNAME_LENGTH){//用户名不能大于16位
					$this->setRegError('用户名必须大于'.MIN_USERNAME_LENGTH.'位并且小于'.MAX_USERNAME_LENGTH.'位');
					return false;
				}
				
				if($checkEmail){
				/*-----------Check email type---------------------------*/
					if($password==$password_confirm){
						if(strlen($password)>25||strlen($password)<6){
							$this->setRegError('用户名必须大于'.MIN_PASSWORD_LENGTH.'位并且小于'.MAX_PASSWORD_LENGTH.'位');
						}
						else{
							$password = encrypt($password);
							$password_confirm = encrypt($password_confirm);
							$activation_key = generateKey();
							$forgot_password_key = generateKey();
							$registered_on = date("Y-m-d H:i:s");
							
							//$queryreg = mysql_query("INSERT INTO `account` (`email`,`password`,`activation_key`,`forgot_pass_key`,`registered_on`)
								//						VALUES('$email','$password','$activation_key','$forgot_password_key','$registered_on')");
							
							DB::insert('account',array(
								'username'			=> $username,
								'email' 			=> $email,
								'password'			=> $password,
								'activation_key' 	=> $activation_key,
								'forgot_pass_key' 	=> $forgot_password_key,
								'registered_on' 	=> $registered_on,
								'is_rookie'			=> 1
							));
							$user_id = DB::insertId();
							
							$this->sendActivationEmail($user_id,$username,$activation_key,$email);
							return $user_id;
							//email已送出，跳转至提示页面
							//js_redirect('恭喜注册成功！',HOME_URL.'user/signup_success.php?uid='.$user_id);
							
						}	
					}
					else {
						$this->setRegError( "两次输入密码不一致" );
					}
				}
				else{
					$this->setRegError( "邮箱的格式错误" );
				}
			}
			else {
				$this->setRegError('请全部填写');
			}
		}
		return false;
	}


	
	/**
	 * 发送激活邮件
	 * @param $user_id
	 * 	注册用户时生成的id
	 * @param $activation_key
	 *  激活码
	 * @param $recipient
	 *  用户邮箱
	 * 
	 */
	function sendActivationEmail($user_id, $username, $activation_key, $recipient){
		$activation_link = HOME_URL.'user/activation.php?id='.$user_id.'&key='.$activation_key;
		$message = str_replace('{activation_link}',$activation_link,file_get_contents(ROOT.'templates/activation_email.php'));
		return sendEmail($recipient, $username, AUTO_EMAIL_ADDRESS, AUTO_EMAIL_NAME, '\(≧▽≦)/用户激活邮件', $message);
	}
	
	/**
	 * 激活用户，
	 * @param $user_id
	 * 	用户id
	 * @param $activation_key
	 * 	激活码
	 * @return 
	 * 	true 激活成功，false 激活失败
	 */
	function activateUser($user_id, $activation_key){
		//check if user informaiton match
		$user_row = DB::queryFirstRow("SELECT * FROM `account` WHERE `activation_key` =%s AND `id`=%i",$activation_key,$user_id);
		
		if($user_row == null){
			echo "用户认证错误";
			return false;
		}
		if($user_row['is_active'] == 1){
			echo '此账户已激活，请点击<a href="'.HOME_URL.'main/">这里</a>登陆';
			return false;
		}
		DB::update('account', 
					array(
						'is_active' => '1'
					), 
					"id=%i", $user_id);
		  
	  	if(DB::affectedRows()==0){
			echo "激活不成功";
			return false;
		}
		
		//激活成功 update activation key
		echo '用户已激活，请点击<a href="'.HOME_URL.'main/">这里</a>登陆';
		return true;
		
	}
	
	/**
	 * 发送忘记密码email
	 * @param $user_id
	 * 	用户id
	 * @param $recipient
	 * 	收件人
	 * @param $forgot_key
	 * 	忘记密码key
	 */
	function sendForgotPassEmail($user_id, $recipient, $forgot_key){
		
	}
	
	/**
	 * 获取master profile
	 * @param $master_id
	 * 	主人id
	 * @return
	 * 	主人资料as an array, null if no results
	 */
	function getMasterProfileById($master_id){
		return DB::queryFirstRow("SELECT * FROM `master_profile` WHERE `id`=%i",$master_id);
	}
	 	
	protected function setLoginError($msg){
		setSession('login_error',$msg);
	}
	protected function setRegError($msg){
		setSession('reg_error',$msg);
	}
}
?>